/**
 * 登录后的用户信息管理及token统一管理
 */
import { clearStorage } from '@/utils/storage';
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
    state: () => ({
        token: '',
        refreshToken: '',
        tenantId: '',
        userInfo: {},
    }),
    actions: {
        // 信息存储
        setToken(data) {
            this.token = data.access_token;
            this.refreshToken = data.refresh_token;
            this.userInfo = data;
            // 可选：持久化到 localStorage
            localStorage.setItem('justech-token', JSON.stringify({ content: data.access_token, dataType: 'string', datetime: Date.now() }));
            localStorage.setItem('justech-refreshToken', JSON.stringify({ content: data.refresh_token, dataType: 'string', datetime: Date.now() }));
            localStorage.setItem('justech-userInfo', JSON.stringify({ content: data, dataType: 'string', datetime: Date.now() }));
        },
        // 清除信息
        clearToken() {
            this.token = '';
            this.refreshToken = '';
            this.userInfo = {};
            // 使用全局方法清除localStorage和cookie
            clearStorage();
        },
        loadTokenFromStorage() {
            const t = JSON.parse(localStorage.getItem('justech-token'));
            const r = JSON.parse(localStorage.getItem('justech-refreshToken'));
            const u = JSON.parse(localStorage.getItem('justech-userInfo'));
            if (t && r) {
                this.token = t.content;
                this.refreshToken = r.content;
                this.userInfo = u;
            }
        }
    }
})
